<template>
    <div class="history">
        <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="轨迹回放" name="first">
                <!-- 查找框 -->
                <div class="box" v-if="boxState">
                  <el-form ref="form" :model="form" label-width="80px">
                    <el-form-item label="查找">
                      <el-input v-model="form.search"></el-input>
                    </el-form-item>
                    <el-form-item label="开始时间">
                      <el-date-picker
                        v-model="form.startTime"
                        type="datetime"
                        placeholder="选择日期时间">
                      </el-date-picker>
                    </el-form-item>
                    <el-form-item label="结束时间">
                      <el-date-picker
                        v-model="form.endTime"
                        type="datetime"
                        placeholder="选择日期时间">
                      </el-date-picker>
                    </el-form-item>
                    <el-form-item label="间距">
                      <el-select v-model="form.spacing">
                        <el-option label="0M" value="0M"></el-option>
                        <el-option label="10M" value="10M"></el-option>
                        <el-option label="100M" value="100M"></el-option>
                        <el-option label="500M" value="500M"></el-option>
                        <el-option label="1KM" value="1KM"></el-option>
                        <el-option label="3KM" value="3KM"></el-option>
                        <el-option label="5KM" value="5KM"></el-option>
                        <el-option label="10KM" value="10KM"></el-option>
                        <el-option label="30KM" value="30KM"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" @click="onSubmit">立即搜索</el-button>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" @click="play(1)">开始</el-button>
                      <el-button type="primary" @click="play(2)">暂停</el-button>
                      <el-button type="primary" @click="play(3)">结束</el-button>
                    </el-form-item>
                  </el-form>
                </div>

                <!-- 收缩按钮 -->
                <el-button class="control-btn" icon="el-icon-search" circle @click="isShow"></el-button>

                <!-- 下载按钮 -->
                <el-button class="down-btn" type="success" icon="el-icon-download" circle @click="exportExcel"></el-button>

                <!-- 地图 -->
                <div id="map"></div>
                <div id="history">
                  <el-table
                    stripe
                    :data="tableData"
                    height="210"
                    :row-style="{height: '10px'}"
                    :cell-style="{padding: '5px 0'}"
                    border
                    style="width: 100%">
                    <el-table-column
                      prop="operation"
                      label="操作"
                      width="80">
                    </el-table-column>
                    <el-table-column
                      type="index"
                      label="序号"
                      width="55">
                    </el-table-column>
                    <el-table-column
                      prop="time"
                      label="时间"
                      width="180">
                    </el-table-column>
                    <el-table-column
                      prop="speed"
                      label="速度"
                      width="120">
                    </el-table-column>
                    <el-table-column
                      prop="timeM"
                      label="当时里程"
                      width="120">
                    </el-table-column>
                    <el-table-column
                      prop="travelM"
                      label="行驶里程"
                      width="120">
                    </el-table-column>
                    <el-table-column
                      prop="position"
                      label="位置"
                      width="180">
                    </el-table-column>
                    <el-table-column
                      prop="state"
                      label="状态"
                      width="360">
                    </el-table-column>
                  </el-table>
                </div>
            </el-tab-pane>
            <el-tab-pane label="录像回放" name="second">录像回放</el-tab-pane>
        </el-tabs>
    </div>
</template>

<script>
import BMap from "BMap"
import historyApi from '@/api/history'
import {export_json_to_excel} from '@/public/Export2Excel'

export default {
    name: "Map",
    data() {
      return {
        activeName: 'first',
        boxState: true,
        tableData: [],
        gpsArr:[{
          longitude: 113.46499,
          latitude: 23.41938
        },{
          longitude: 113.46469,
          latitude: 23.4191
        },{
          longitude: 113.46627,
          latitude: 23.4183
        },{
          longitude: 113.47355,
          latitude: 23.41556
        },{
          longitude: 113.47972,
          latitude: 23.40971
        }],//后台拿到的gps点数组
        speed:4000,//速度
        lushu:{},//路书
        mycarId:'京123465',
        myMap: {}, //地图
        form: {
          search: '',
          startTime: '',
          endTime: '',
          spacing: '0M',
          play: '显示轨迹点'
        }
      };
    },
    methods: {
      // 点击按钮使搜索框出现和消失
      isShow() {
        if(this.boxState){
          this.boxState = false
        }else{
          this.boxState = true
        }
      },

      // 搜索按钮
      onSubmit() {
        historyApi.getHistoryData(this.form).then(response => {
          const resp = response.data
          if(resp.flag){
            this.tableData = resp.data.rows
            this.gpsArr = resp.data.gpsArr
            this.mycarId = resp.data.searchCar
            this.initMap()
          }else{
            this.$message({
              message: resp.message,
              type: 'warning'
            })
          }
        })
      },

      // 导出Excel表格
      exportExcel(){
        require.ensure([], () => {
          const tHeader = ['操作', '时间', '速度', '当时里程', '行驶里程', '位置', '状态']
          const filterVal = ['operation', 'time', 'speed', 'timeM', 'travelM', 'postion', 'state']
          const list = this.tableData
          const data = this.formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, '历史轨迹')
        })
      },
      formatJson(filterVal, jsonData){
        return jsonData.map(v => filterVal.map(j => v[j]))
      },

      handleClick(tab, event) {
        console.log(tab, event);
      },

      createMap () {
        var map = new BMap.Map("map")
        var point = new BMap.Point(113.457261, 23.161446)
        map.centerAndZoom(point, 16)
        map.enableScrollWheelZoom(true)
        map.addControl(new BMap.NavigationControl());    
        map.addControl(new BMap.ScaleControl());    
        map.addControl(new BMap.OverviewMapControl());    
        map.addControl(new BMap.MapTypeControl({mapTypes: [BMAP_NORMAL_MAP,BMAP_SATELLITE_MAP ]}));
      },

      initMap () {
        var map = new BMap.Map("map")
        var point = new BMap.Point(this.gpsArr[0].longitude, this.gpsArr[0].latitude)
        map.centerAndZoom(point, 16)
        map.enableScrollWheelZoom(true)
        map.addControl(new BMap.NavigationControl());    
        map.addControl(new BMap.ScaleControl());    
        map.addControl(new BMap.OverviewMapControl());    
        map.addControl(new BMap.MapTypeControl({mapTypes: [BMAP_NORMAL_MAP,BMAP_SATELLITE_MAP ]}));

        var arrPois = [];
        for(let i=0; i<this.gpsArr.length; i++){
          var p0 = this.gpsArr[i].longitude;
          var p1 = this.gpsArr[i].latitude;
          var point = new BMap.Point(p0, p1);
          arrPois.push(point);
        }

        //画轨迹
        var polyLine = new BMap.Polyline(arrPois, {
          strokeColor: 'blue',
          strokeWeight: 5,
          strokeOpacity: 0.5
        });
        map.addOverlay(polyLine);

        BMapLib.LuShu.prototype._move = function(initPos, targetPos, effect){
          var pointsArr = [initPos, targetPos]; //点组数
          var me = this,
          currentCount = 0, //当前帧数
          timer = 10, //步长，米/秒
          step = this._opts.speed / (1000 / timer),
          // 初始坐标
          init_pos = this._projection.lngLatToPoint(initPos),
          //获取结束点的(x,y)坐标
          target_pos = this._projection.lngLatToPoint(targetPos),
          //总的步长
          count = Math.round(me._getDistance(init_pos, target_pos) / step);

          if(count < 1){
            me._moveNext(++me.i);
            return;
          }
          me._intervalFlag = setInterval(function() {
            //两点之间当前帧数大于总帧数的时候，则说明已经完成移动
            if(currentCount >= count){
              clearInterval(me._intervalFlag);
              //移动的点已经超过总的长度
              if(me.i > me._path.length){
                return;
              }
              //运行下一个点
              me._moveNext(++me.i);
            }else{
              currentCount++;
              var x = effect(init_pos.x, target_pos.x, currentCount, count),
              y = effect(init_pos.y, target_pos.y, currentCount, count),
              pos = me._projection.pointToLngLat(new BMap.Pixel(x, y));
              //设置marker
              if(currentCount == 1){
                var proPos = null;
                if(me.i - 1 >= 0){
                  proPos = me._path[me.i - 1];
                }
                if(me._opts.enableRotation == true){
                  me.setRotation(proPos, initPos, targetPos);
                }
                if(me._opts.autoView){
                  if(!me._map.getBounds().containsPoint(pos)){
                    me._map.setCenter(pos);
                  }
                }
              }
              //正在移动
              me._marker.setPosition(pos);
              // 设置自定义overlay的位置
              me._setInfoWin(pos);
            }
          }, timer);
        };
        this.initLushu(map, arrPois, this.mycarId);
      },

      initLushu(map, arrPois, mycarId){
        this.lushu = new BMapLib.LuShu(map, arrPois, {
          defaultContent: mycarId,
          autoView: true,
          icon: new BMap.Icon(
            "http://developer.baidu.com/map/jsdemo/img/car.png",
            new BMap.Size(52, 26),
            {
              anchor: new BMap.Size(27, 13)
            }),
            speed: this.speed,
            enableRotation: true,
            landmarkPois: [
              {
                lng: 116.306954,
                lat: 40.05718,
                html: '加油站',
                pauseTime: 2
              }
            ]
        });
      },
      play(val){
        if(this.arrIndex >= this.gpsArr.length - 3){
          this.arrIndex = 0;
        }
        switch (val){
          case 1:
            this.lushu.start();
            break;
          case 2:
            this.lushu.pause();
            break;
          case 3: {
            this.lushu.stop();
            this.arrIndex = 0;
            this.percentage = 0;
            break;
          }
        }
      },
    },
    mounted() {
        this.createMap()
    }
}
</script>

<style scoped>
.history{
    padding: 5px 5px 0 5px;
}
#map{
    width: 100%;
    height: 400px;
}
#history{
  width: 100%;
  height: 210px;
  background-color: pink;
  overflow-x: auto;
  overflow-y: auto;
}

.el-tab-pane{
  position: relative;
}
.box{
  z-index: 100;
  right: 0;
  padding: 20px;
  background-color: rgb(255, 255, 255, 0.8);
  position: absolute;
}
.control-btn{
  z-index: 1000;
  position: absolute;
  right: 10px;
  top: 340px;
}
.down-btn{
  z-index: 1000;
  position: absolute;
  right: 10px;
  top: 410px;
}
</style>